<template>
  <div>
    <el-card shadow="never" class="d2-mb">
      <el-form class="filter-container" label-width="85px">
        <el-row :gutter="20" style="height:30px">
          <el-col :span="5">
            <el-form-item label="策略名称">
              <el-input
                placeholder="请输入内容"
                v-model="searchData.strategy_name"
                clearable
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="策略名称ID">
              <el-input
                placeholder="请输入内容"
                v-model="searchData.strategy_id"
                clearable
                type="number"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="策略类型">
              <el-select
                v-model="searchData.strategy_type"
                placeholder="请选择"
                style="width:100%;"
                clearable
              >
                <el-option label="现货期货套期" value="1"></el-option>
                <el-option label="现货现货套期" value="2"></el-option>
                <el-option label="现货期权套期" value="3"></el-option>
                <el-option label="现货场外期权套期" value="7"></el-option>
                <el-option label="期货期货套利" value="4"></el-option>
                <el-option label="现货单边" value="5"></el-option>
                <el-option label="期货单边" value="6"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="策略目的">
              <el-select
                v-model="searchData.strategy_objective"
                placeholder="请选择"
                style="width:100%;"
                clearable
              >
                <el-option label="期货套利" value="1"></el-option>
                <el-option label="期现套利" value="2"></el-option>
                <el-option label="套期保值" value="3"></el-option>
                <el-option label="其他" value="4"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="部门名称">
              <el-input
                placeholder="请输入内容"
                v-model="searchData.department_name"
                clearable
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="申请人">
              <el-input
                placeholder="请输入内容"
                v-model="searchData.creator"
                clearable
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="状态">
              <el-select
                v-model="searchData.status"
                placeholder="请选择"
                style="width:100%;"
                clearable
              >
                <el-option label="草拟" value="0"></el-option>
                <el-option label="审核中" value="1"></el-option>
                <el-option label="已驳回" value="2"></el-option>
                <el-option label="已退审" value="3"></el-option>
                <el-option label="已通过" value="4"></el-option>
                <el-option label="已失效" value="5"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-button
              type="primary"
              size="mini"
              @click="search"
              style="margin-top:5px"
            >
              <d2-icon name="search" /> 查询
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <div class="mb">
      <el-button type="default" size="mini" @click="dialogVisible = true">
        <d2-icon name="plus" />
        新增
      </el-button>
      <el-button type="default" size="mini" @click="edit('alter')">
        <d2-icon name="edit" />
        修改
      </el-button>
      <el-button type="default" size="mini" icon="el-icon-delete" @click="del">
        删除
      </el-button>
      <el-button type="default" size="mini" @click="edit('check')">
        <d2-icon name="search" />
        查看
      </el-button>
      <el-button type="default" size="mini" @click="edit('copy')">
        <d2-icon name="clone" />
        复制
      </el-button>
      <el-button type="default" size="mini" @click="submitApproval">
        <d2-icon name="upload" />
        提交审批
      </el-button>
      <el-button type="default" size="mini" @click="retired">
        <d2-icon name="reply" />
        退审
      </el-button>
      <el-button type="default" size="mini" @click="historicalApproval">
        <d2-icon name="history" />
        审批历史
      </el-button>
      <el-button type="default" size="mini" @click="edit('change')">
        <d2-icon name="exchange" />
        变更
      </el-button>
      <el-button type="default" size="mini" @click="refresh">
        <d2-icon name="refresh" />
        刷新
      </el-button>
    </div>
    <el-dialog
      title="策略类型"
      :visible.sync="dialogVisible"
      width="30%"
      :append-to-body="true"
    >
      <el-radio-group v-model="radioType">
        <el-radio :label="1">现货期货套期</el-radio>
        <el-radio :label="2">现货现货套期</el-radio>
        <el-radio :label="3">现货期权套期</el-radio>
        <el-radio :label="7" style="margin-left: 14px;"
          >现货场外期权套期</el-radio
        >
        <el-radio :label="4">期货期货套利</el-radio>
        <el-radio :label="5" style="margin-left: -13px;">现货单边</el-radio>
        <el-radio :label="6" style="margin-left: -13px;">期货单边</el-radio>
      </el-radio-group>
      <span span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="mini">取 消</el-button>
        <el-button type="primary" @click="add" size="mini">确 定</el-button>
      </span>
    </el-dialog>
    <el-card shadow="never" class="d2-mb">
      <el-table
        :data="tableData"
        border
        :cell-style="{ 'text-align': 'center' }"
        :header-cell-style="{
          background: '#eef1f6',
          'text-align': 'center',
          color: '#606266'
        }"
        highlight-current-row
        @row-click="handleSelectionChange"
      >
        <el-table-column type="index" label="序号"> </el-table-column>
        <el-table-column prop="status" label="状态"></el-table-column>
        <el-table-column
          prop="org_name"
          label="机构名称"
          :formatter="orgFormat"
        ></el-table-column>
        <el-table-column prop="depart_name" label="部门名称"></el-table-column>
        <el-table-column
          prop="strategy_name"
          label="策略名称"
        ></el-table-column>
        <el-table-column
          prop="strategy_id"
          label="策略ID"
          sortable
        ></el-table-column>
        <el-table-column
          prop="strategy_type"
          label="策略类型"
        ></el-table-column>
        <el-table-column
          prop="strategy_objective"
          label="策略目的"
        ></el-table-column>
        <el-table-column
          prop="max_occupation_funds"
          label="最大占用资金"
        ></el-table-column>
        <el-table-column prop="loss_limit" label="损失限额"></el-table-column>
        <el-table-column
          prop="profit_expectation"
          label="预期盈利"
        ></el-table-column>
        <el-table-column
          prop="risk_profit_ratio"
          label="风险利润比"
        ></el-table-column>
        <el-table-column
          prop="expected_return_on_investment"
          label="预期投资回报"
        ></el-table-column>
        <el-table-column
          prop="strategy_hierarchy"
          label="策略层级"
        ></el-table-column>
        <el-table-column
          prop="strategy_formulate_date"
          label="策略制定日期"
          sortable
        >
          <template slot-scope="scope">{{
            scope.row.strategy_formulate_date | dateYMDHMSFormat
          }}</template>
        </el-table-column>
        <el-table-column
          prop="strategy_start_date"
          label="策略开始日期"
          sortable
        ></el-table-column>
        <el-table-column
          prop="strategy_end_date"
          label="策略结束日期"
          sortable
        ></el-table-column>
        <el-table-column prop="creator_name" label="申请人"></el-table-column>
      </el-table>
    </el-card>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="searchData.page"
      :page-size="searchData.pageSize"
      layout="total, prev, pager, next"
      :total="searchData.totalPage"
    >
    </el-pagination>
    <el-dialog :visible.sync="submitApprovals" title="提交审批">
      <submit-approval :rowaa="row"></submit-approval>
      <span span slot="footer" class="dialog-footer">
        <el-button @click="submitApprovals = false">取 消</el-button>
        <el-button type="primary">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="historicalApprovals" title="审批历史">
      <historical-approval :rowaa="row"></historical-approval>
      <span span slot="footer" class="dialog-footer">
        <el-button @click="historicalApprovals = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import submitApproval from "../tactical_management/master/model/submitApproval.vue";
import historicalApproval from "../tactical_management/master/model/historicalApproval.vue";
import { strategyInfo } from "@/api/url_info.js";
import { addStrategy } from "@/api/url_info.js";
import { tradeInfo } from "@/api/url_info.js";
import { approval } from "@/api/url_info.js";
export default {
  //策略管理
  name: "strategicManagement",
  components: {
    "historical-approval": historicalApproval,
    "submit-approval": submitApproval
  },
  data() {
    return {
      dialogVisible: false,
      historicalApprovals: false,
      submitApprovals: false,
      radioType: 1,
      row: "",
      tableData: [],
      spotDatas: [],
      futureDatas: [],
      searchData: {
        page: 1, //当前页
        pageSize: 20,
        totalPage: 0,
        strategy_name: "",
        strategy_id: "",
        creator: "",
        status: "",
        department_name: "",
        strategy_objective: "",
        strategy_type: ""
      },
      // 表格选中row数据
      multipleSelection: {}
    };
  },
  created: function() {
    this.strategyInfo();
  },
  methods: {
    // 机构
    orgFormat(row, column) {
      return row.org_name == null ? row.depart_name : row.org_name;
    },
    // 清空当前页缓存并刷新此页面
    refresh() {
      this.searchData.searchData = "";
      this.searchData.strategy_id = "";
      this.searchData.strategy_name = "";
      this.searchData.creator = "";
      this.searchData.status = "";
      this.searchData.department_name = "";
      this.searchData.strategy_objective = "";
      this.searchData.strategy_type = "";
      this.multipleSelection = "";
      this.strategyInfo();
    },
    //新增
    add() {
      this.dialogVisible = false;
      if (this.radioType === 1) {
        this.$router.push({ path: "/spotFuturesHedging" });
      } else if (this.radioType === 2) {
        this.$router.push({ path: "/spotHedging" });
      } else if (this.radioType === 3) {
        this.$router.push({ path: "/spotOptionHedging" });
      } else if (this.radioType === 4) {
        this.$router.push({ path: "/futuresArbitrage" });
      } else if (this.radioType === 5) {
        this.$router.push({ path: "/spotUnilateral" });
      } else if (this.radioType === 6) {
        this.$router.push({ path: "/futuresUnilateral" });
      } else if (this.radioType === 7) {
        this.$router.push({ path: "/overCounterOption" });
      }
    },
    // 每页数
    handleSizeChange(val) {
      this.searchData.pageSize = val;
      this.searchData.page = 1;
      this.strategyInfo();
    },
    // 当前页
    handleCurrentChange(val) {
      this.searchData.page = val;
      this.strategyInfo();
    },
    //提交审批
    submitApproval(row) {
      // this.submitApprovals = true;
      // this.row = row;
      let objToStr = JSON.stringify(this.multipleSelection);
      if (this.multipleSelection.strategy_id) {
        if (this.multipleSelection.status == "已驳回") {
          this.$message({
            message: "已驳回状态不能提交审批",
            type: "warning"
          });
        } else {
          let params = {
            operation: "ADD",
            business_id: this.multipleSelection.strategy_id,
            desc: objToStr,
            task: "SLG"
          };
          approval(params)
            .then(res => {
              this.strategyInfo();
              this.$message({
                message: res.result,
                type: "success"
              });
            })
            .catch(err => {
              this.$message.error(err.msg);
            });
        }
      } else {
        this.$message({
          message: "请选择一条数据",
          type: "warning"
        });
      }
    },
    //审批历史
    historicalApproval(row) {
      if (this.multipleSelection.strategy_id) {
        if (this.multipleSelection.workOrderID == "0") {
          this.$message({
            message: "未进入审批历史",
            type: "warning"
          });
        } else {
          this.$router.push(
            "/examine_historyss?id=" + this.multipleSelection.workOrderID
          );
        }
      } else {
        this.$message({
          message: "请选择一条数据",
          type: "warning"
        });
      }
    },
    //退审
    retired() {
      if (this.multipleSelection.strategy_id) {
        if (this.multipleSelection.status == "审核中") {
          let params = {
            operation: "MOD",
            id: this.multipleSelection.workOrderID,
            status: 3,
            opinion: ""
          };
          approval(params)
            .then(res => {
              this.strategyInfo();
              this.$message({
                message: res.result,
                type: "success"
              });
            })
            .catch(err => {
              this.$message.error(err.msg);
            });
        } else {
          this.$message({
            message: "只有状态为“审核中”的策略才能退审",
            type: "warning"
          });
        }
      } else {
        this.$message({
          message: "请选择一条数据",
          type: "warning"
        });
      }
    },
    //查询
    search() {
      this.searchData.page = 1;
      this.strategyInfo();
    },
    //网格信息
    strategyInfo() {
      strategyInfo(this.searchData)
        .then(res => {
          this.tableData = [];
          let data = res.result.results;
          this.searchData.totalPage = res.result.count;
          for (let i = 0; i < data.length; i++) {
            this.tableData[i] = {
              status: data[i]["status"],
              org_name: data[i]["org_name"],
              depart_name: data[i]["depart_name"],
              strategy_name: data[i]["strategy_name"],
              strategy_id: data[i]["strategy_id"],
              strategy_type: data[i]["strategy_type"],
              strategy_objective: data[i]["strategy_objective"],
              max_occupation_funds: data[i]["max_occupation_funds"],
              loss_limit: data[i]["loss_limit"],
              profit_expectation: data[i]["profit_expectation"],
              risk_profit_ratio: data[i]["risk_profit_ratio"],
              expected_return_on_investment:
                data[i]["expected_return_on_investment"],
              strategy_hierarchy: data[i]["strategy_hierarchy"],
              strategy_formulate_date: data[i]["strategy_formulate_date"],
              strategy_start_date: data[i]["strategy_start_date"],
              strategy_end_date: data[i]["strategy_end_date"],
              creator_name: data[i]["creator_name"],
              department_name: data[i]["department_name"],
              hedging_ratio_lower: data[i]["hedging_ratio_lower"],
              hedging_ratio_upper: data[i]["hedging_ratio_upper"],
              strategy_type: data[i]["strategy_type"],
              hedging_method: data[i]["hedging_method"],
              strategy_description: data[i]["strategy_description"],
              workOrderID: data[i]["workOrderID"]
            };
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    //选中的一行数据
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //删除
    del() {
      let that = this;
      let data = {
        operation: "DEL",
        strategy_id: that.multipleSelection.strategy_id
      };

      if (data.strategy_id) {
        if (
          that.multipleSelection.status == "草拟" ||
          that.multipleSelection.status == "已驳回"
        ) {
          that
            .$confirm("是否要删除？", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            })
            .then(() => {
              addStrategy(data)
                .then(res => {
                  that.searchData.page = 1;
                  that.refresh();
                  that.$message({
                    message: res.result,
                    type: "success"
                  });
                })
                .catch(err => {
                  that.$message.error(err.msg);
                });
            });
        } else {
          that.$message({
            message: "只有状态为“草拟”和“已驳回”的策略可以删除",
            type: "warning"
          });
        }
      } else {
        that.$message({
          message: "请选择一条数据",
          type: "warning"
        });
      }
    },
    //编辑信息
    async editInfo(state) {
      let that = this;
      let datas = that.multipleSelection;
      let spotDatas = [];
      let futureDatas = [];
      await tradeInfo({ strategy_id: datas.strategy_id })
        .then(res => {
          let data = res.result;
          for (let i = 0; i < data.length; i++) {
            if (data[i]["trade_type"] == 1) {
              spotDatas[i] = {
                commodity_unit: data[i]["commodity_unit"],
                created_time: data[i]["created_time"],
                depart_name: data[i]["depart_name"],
                currency: data[i]["currency"],
                direction: data[i]["direction"],
                max_amount: data[i]["max_amount"],
                max_volume: data[i]["max_volume"],
                name: data[i]["name"].id,
                name_cn: data[i]["name"].name,
                reference_price: data[i]["reference_price"],
                remarks: data[i]["remarks"],
                type: data[i]["type"],
                trade_type: data[i]["trade_type"],
                premium_received_paid: data[i]["premium_received_paid"],
                spare_value: data[i]["spare_value"],
                strategy_id: data[i]["strategy_id"],
                strategy_name: data[i]["strategy_name"]
              };
            } else if (
              data[i]["trade_type"] == 2 ||
              data[i]["trade_type"] == 3
            ) {
              futureDatas[i] = {
                commodity_unit: data[i]["commodity_unit"],
                created_time: data[i]["created_time"],
                depart_name: data[i]["depart_name"],
                currency: data[i]["currency"],
                direction: data[i]["direction"],
                instrument: data[i]["instrument"],
                max_amount: data[i]["max_amount"],
                max_volume: data[i]["max_volume"],
                offset_flag: data[i]["offset_flag"],
                reference_price: data[i]["reference_price"],
                remarks: data[i]["remarks"],
                productName: data[i]["productName"],
                productID: data[i]["productID"],
                type: data[i]["type"],
                trade_type: data[i]["trade_type"],
                premium_received_paid: data[i]["premium_received_paid"],
                spare_value: data[i]["spare_value"],
                strategy_id: data[i]["strategy_id"],
                strategy_name: data[i]["strategy_name"],
                volumeMultiple: data[i]["volumeMultiple"]
              };
            }
          }
        })
        .catch(err => {
          that.$message.error(err.msg);
        });
      that.spotDatas = spotDatas;
      that.futureDatas = futureDatas.filter(item => {
        return item !== "";
      });
      if (datas.strategy_type === "现货期货套期") {
        that.$router.push({
          path: "/spotFuturesHedging_E",
          query: { strategy_id: datas.strategy_id, state: state }
        });
      }
      if (datas.strategy_type === "现货现货套期") {
        that.$router.push({
          path: "/spotHedging_E",
          query: { strategy_id: datas.strategy_id, state: state }
        });
      }
      if (datas.strategy_type === "现货期权套期") {
        that.$router.push({
          path: "/spotOptionHedging_E",
          query: { strategy_id: datas.strategy_id, state: state }
        });
      }
      if (datas.strategy_type === "期货期货套利") {
        that.$router.push({
          path: "/futuresArbitrage_E",
          query: { strategy_id: datas.strategy_id, state: state }
        });
      }
      if (datas.strategy_type === "现货单边") {
        that.$router.push({
          path: "/spotUnilateral_E",
          query: { strategy_id: datas.strategy_id, state: state }
        });
      }
      if (datas.strategy_type === "期货单边") {
        that.$router.push({
          path: "/futuresUnilateral_E",
          query: { strategy_id: datas.strategy_id, state: state }
        });
      }
      if (datas.strategy_type === "现货场外期权套期") {
        that.$router.push({
          path: "/overCounterOption_E",
          query: { strategy_id: datas.strategy_id, state: state }
        });
      }
    },
    //修改/查看
    edit(state) {
      let that = this;
      let data = that.multipleSelection;
      if (data.strategy_id) {
        if (state == "alter") {
          if (data.status == "草拟" || data.status == "已驳回") {
            that.editInfo(state);
          } else {
            that.$message({
              message: "只有状态为“草拟”和“已驳回”的策略可以修改",
              type: "warning"
            });
          }
        } else if (state == "change") {
          if (data.status == "已通过") {
            that.editInfo(state);
          } else {
            that.$message({
              message: "只有状态为“已通过”的策略可以变更",
              type: "warning"
            });
          }
        } else {
          that.editInfo(state);
        }
      } else {
        that.$message({
          message: "请选择一条数据",
          type: "warning"
        });
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.el-radio {
  width: 100%;
  text-align: center;
  margin-top: 15px;
}
.el-form-item {
  margin-bottom: 15px !important;
}
</style>
